package com.qinglei.recoup.system.handler;

import com.qinglei.recoup.common.utils.JsonUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class MysqlJsonArrayHandler<T> extends BaseTypeHandler<List<T>> {
    private Class<T> type;

    public MysqlJsonArrayHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<T> integers, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JsonUtils.objectToJson(integers));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String strVal = resultSet.getString(s);
        if (null != strVal) {
            return JsonUtils.jsonToList(strVal, this.type);
        }
        return null;
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String strVal = resultSet.getString(i);
        if (null != strVal) {
            return JsonUtils.jsonToList(strVal, this.type);
        }
        return null;
    }

    @Override
    public List<T> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String strVal = callableStatement.getString(i);
        if (null != strVal) {
            return JsonUtils.jsonToList(strVal, this.type);
        }
        return null;
    }
}
